<template>
  <div>
    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="8">
          <el-input
            v-model="searchTitle"
            placeholder="请输入标题关键词搜索"
            clearable
            @input="handleSearch"
            @clear="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
          </el-input>
        </el-col>

      </el-row>
    </div>

    <div class="addBtn">

      <!-- <el-button type="primary" @click="handleButtonAdd()">+ 添加</el-button> -->
      <el-dialog title="添加" :visible.sync="dialogTableVisible" :before-close="closeFormData">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">

          <el-form-item label="选择专家" prop="zhuanjia">
            <el-button type="primary" @click="showExpertSelector = true">请选择</el-button>

            <div v-if="ruleForm.expert && ruleForm.expert.id" class="zhuanjia-info">
              <img :src="ruleForm.expert.avatar" alt="">
              {{ ruleForm.expert.nickname }}
            </div>
          </el-form-item>
          <el-form-item label="文章标题" prop="name">
            <el-input v-model="ruleForm.title" />
          </el-form-item>

          <el-form-item label="封面" prop="cover">
            <ImgCutter :cut-width="400" :cut-height="200" @cutDown="cutDown">
              <template #open />
            </ImgCutter>
            <el-image
              v-if="dialogImageUrl"
              style="width: 200px; height: 100px; margin-top: 10px"
              :src="dialogImageUrl"
              fit="cover"
            />
          </el-form-item>

          <el-form-item label="微信分享封面" prop="cover">
            <ImgCutter :cut-width="500" :cut-height="400" @cutDown="cutDown1">
              <template #open />
            </ImgCutter>
            <el-image
              v-if="dialogImageUrl1"
              style="width: 500px; height: 400px; margin-top: 10px"
              :src="dialogImageUrl1"
              fit="cover"
            />
          </el-form-item>

          <el-form-item label="分类">
            <!-- <el-radio-group v-model="ruleForm.type" ref="radio">
                            <el-radio v-for="(item,index) in inforType" :key="index" :label="item.id">{{ item.text }}</el-radio>
                        </el-radio-group> -->
            <el-checkbox-group v-model="ruleForm.type">

              <el-checkbox v-for="(item, index) in inforType.slice(0, 3)" :key="index" :label="item.id">
                {{ item.text }}
              </el-checkbox>

            </el-checkbox-group>

            <!-- <el-radio-group v-model="ruleForm.type" >
                            <el-radio v-for="(item,index) in inforType" :key="index" :label="item.id">{{ item.text }}</el-radio>
                        </el-radio-group> -->
          </el-form-item>
          <el-form-item label="文章内容" prop="name">
            <!-- <quill-editor ref="myQuillEditor" :options="quillOption" v-model="ruleForm.content">
                        </quill-editor> -->
            <!--  -->
            <div v-if="isVisible">
              <WangEditor :content="contentData" @submit="workVadeUpdate" />
            </div>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="ruleForm.sort" />
          </el-form-item>
          <el-form-item label="显示">
            <el-radio-group v-model="ruleForm.status">
              <el-radio :label="1">显示</el-radio>
              <el-radio :label="2">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>

        </el-form>
        <div style="text-align: right;">
          <el-button @click="clickDelete">取消</el-button>
          <el-button type="primary" @click="clickConfirm">确认</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 加载动画 -->
    <div v-loading="loading" element-loading-text="正在加载数据..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" style="min-height: 400px;">
      <el-table :data="tableData" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }">

        <el-table-column prop="title" label="标题" align="center" />
        <el-table-column label="封面" align="center">
          <template slot-scope="scope">
            <img style="width: 120px;height: 120px;" :src="scope.row.cover" alt="">
          </template>
        </el-table-column>

        <el-table-column prop="update_time" label="发布时间" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.update_time) }}
          </template>

        </el-table-column>
        <el-table-column prop="create_time" label="ai修改时间" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="来源" align="center">
          <template slot-scope="scope">
            <span style="color:blue;">
              {{ parseSouce(scope.row.souceurl) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="源资讯地址" align="center">
          <template slot-scope="scope">
            <a v-if="scope.row.souceurl" style="color: red;" :href="scope.row.souceurl">源地址,点击跳转</a>
            <span v-else>
              暂无
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="type" label="资讯类型" align="center">
          <template slot-scope="scope">
            <span>
              {{ scope.row.type === 'lanqiu' ? '🏀 篮球' : '⚽ 足球' }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="handleButton1Click(scope.row, scope.row.type)">发布到平台</el-button>

          </template>
        </el-table-column>

      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="tabListPage">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        style="text-align: center; margin-top: 20px;"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <ExpertSelector :visible.sync="showExpertSelector" @select="handleExpertSelect" />
  </div>

</template>

<script>
import { newsModify, getConfigList, newsDelete } from '../../../libs/api'
import quillConfig from '../../../libs/quill-config.js'
import WangEditor from '@/components/richText'
import ExpertSelector from '@/components/ExpertSelector.vue'
import ImgCutter from 'vue-img-cutter'
import axios from 'axios'
export default {
  components: {
    WangEditor,
    ExpertSelector,
    ImgCutter
  },
  data() {
    return {
      mtype: 0,
      rules: {
        // name: [
        //     { required: true, message: '请输入名称', trigger: 'blur' },
        // ],
      },
      quillOption: quillConfig,
      dialogImageUrl: '',
      dialogImageUrl1: '',
      dialogVisible: false,
      ruleForm: {
        type: [],
        expert: {}
      },
      tableData: [],
      dialogTableVisible: false,
      alltableData: [],
      currentPage: 1,
      totalCount: 0,
      pageSize: 5,
      pageSizes: [5, 10, 20, 50],
      searchTitle: '',
      selectedType: '',
      searchTimer: null,
      content: '',
      inforType: [],
      contentData: '',
      type: 0,
      isVisible: false,
      types: [],
      showExpertSelector: false,
      loadingInstance: null,
      loading: false,
      tmpFoot: `<p><br></p><p><br></p><p><br></p><p><span style="color: rgb(140, 140, 140); font-size: 12px;">来源：有球体育、星球客、310大师APP</span></p><p class="footer"><span style="color: rgb(140, 140, 140); font-size: 12px;">声明：此文版权归原作者所有，若有来源错误或者侵犯您的合法权益，您可通过邮箱与我们取得联系，我们将及时进行处理。</span></p><p><span style="color: rgb(140, 140, 140); font-size: 12px;">邮箱地址：wxb20230710@163.com</span></p>`
    }
  },
  created() {
    this.loadData()
    this.getConfigListData()
  },
  mounted() {
    // this.$refs.radio.$children.forEach((item) => {
    //     item.$refs.radio.removeAttribute("aria-hidden");
    // });
  },
  methods: {
    parseSouce(url) {
      if (url.indexOf('zhibo8') !== -1) {
        return '直播吧'
      }
      if (url.indexOf('dongqiudi') !== -1) {
        return '懂球帝'
      }
      return '其他'
    },
    formatDate(dateStr, includeTime = true) {
      const date = new Date(dateStr)

      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')

      if (!includeTime) {
        return `${year}-${month}-${day}`
      }

      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    selectType(v) {
      if (v) {
        this.getLanqiu()
      } else {
        this.getZuqiu()
      }
    },
    // 搜索处理
    handleSearch() {
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }

      // 设置新的定时器，实现防抖
      this.searchTimer = setTimeout(() => {
        this.currentPage = 1 // 搜索时重置到第一页
        this.loadData()
      }, 500)
    },
    // 类型筛选处理
    handleTypeChange() {
      this.currentPage = 1 // 切换类型时重置到第一页
      this.loadData()
    },
    // 统一的数据加载方法
    loadData() {
      if (this.selectedType === 'lanqiu') {
        this.getLanqiu()
      } else if (this.selectedType === 'zuqiu') {
        this.getZuqiu()
      } else {
        // 默认加载足球数据
        this.getZuqiu()
      }
    },
    extractKeyInfo(dom, type) {
      console.log(dom)

      // 提取图片信息
      const srcs = dom.querySelectorAll('a')

      if (srcs.length) {
        const arr = []

        for (let index = 0; index < srcs.length; index++) {
          arr.push({
            src: srcs[index].href,
            title: srcs[index].querySelector('.title').innerText,
            img: srcs[index].querySelector('img').src,
            date: srcs[index].querySelector('.publish-time').innerText,
            type
          })
        }

        console.log()
        return arr
      }

      return []
    },
    getLanqiu() {
      this.loading = true
      const params = {
        title: this.searchTitle,
        page: this.currentPage,
        pageSize: this.pageSize
      }

      console.log('getLanqiu API调用参数:', params)
      axios.get('https://houtaiai.zctj16888.com/getAinews', { params }
      ).then(res => {
        console.log('getLanqiu 完整响应:', res)
        console.log('getLanqiu res.data:', res.data)
        console.log('getLanqiu res.data.data.list:', res.data.data.list)
        console.log('getLanqiu res.data.data.pagination:', res.data.data.pagination)

        this.tableData = res.data.data.list || []
        this.totalCount = res.data.data.pagination?.total || 0
        console.log('设置的数据:', this.tableData)
        console.log('设置的总数:', this.totalCount)
        this.loading = false
      }).catch(erro => {
        console.log('getLanqiu API错误:', erro)
        this.loading = false
      })
    },
    getZuqiu() {
      this.loading = true
      const params = {
        title: this.searchTitle,
        page: this.currentPage,
        pageSize: this.pageSize
      }

      console.log('getZuqiu API调用参数:', params)
      axios.get('https://houtaiai.zctj16888.com/getAinews', { params }
      ).then(res => {
        console.log('getZuqiu 完整响应:', res)
        console.log('getZuqiu res.data:', res.data)
        console.log('getZuqiu res.data.data.list:', res.data.data.list)
        console.log('getZuqiu res.data.data.pagination:', res.data.data.pagination)

        this.tableData = res.data.data.list || []
        this.totalCount = res.data.data.pagination?.total || 0
        console.log('设置的数据:', this.tableData)
        console.log('设置的总数:', this.totalCount)
        this.loading = false
      }).catch(erro => {
        console.log('getZuqiu API错误:', erro)
        this.loading = false
      })
    },
    async cutDown1(v) {
      const formData = new FormData()
      // 添加文件到表单数据
      formData.append('image', v.file)

      try {
        const response = await axios.post('https://api.zctj16888.com/admin/v1/image/ossUpload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        // 上传成功后更新表单中的封面地址
        console.log(response)
        this.dialogImageUrl1 = response.data.data.url
        this.$message.success('封面上传成功')
      } catch (error) {
        console.error('封面上传失败', error)
        this.$message.error('封面上传失败，请重试')
      }
    },
    async cutDown(v) {
      const formData = new FormData()
      // 添加文件到表单数据
      formData.append('image', v.file)

      try {
        const response = await axios.post('https://api.zctj16888.com/admin/v1/image/ossUpload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        // 上传成功后更新表单中的封面地址
        console.log(response)
        this.dialogImageUrl = response.data.data.url
        this.$message.success('封面上传成功')
      } catch (error) {
        console.error('封面上传失败', error)
        this.$message.error('封面上传失败，请重试')
      }
    },
    handleExpertSelect(v) {
      this.ruleForm.expert = v
    },
    closeFormData() {
      Object.assign(this.ruleForm, {
        title: '',
        type: '',
        sort: '',
        status: ''
      })
      this.isVisible = false
      this.dialogTableVisible = false
      this.contentData = ''
    },
    workVadeUpdate(content) {
      this.ruleForm.content = content
    },
    getConfigListData() {
      getConfigList({

      }).then(res => {
        console.log(res)
        this.inforType = res.data.infoTypeList
      })
    },
    // 显示第几页
    handleCurrentChange(val) {
      // 改变默认的页数
      this.currentPage = val
      this.loadData()
    },
    // 分页
    // 每页显示的条数
    handleSizeChange(val) {
      // 改变每页显示的条数
      this.pageSize = val
      // 改变每页显示的条数时，要将页码显示到第一页
      this.currentPage = 1
      this.loadData()
    },
    getNewsList() {
      this.$message('发布成功，请前往列表查看')
    },
    deleteImg() {
      this.dialogImageUrl = ''
    },
    clickConfirm() {
      this.isVisible = false
      this.contentData = ''
      if (this.type === 0) {
        newsModify({
          title: this.ruleForm.title,
          img_url: this.dialogImageUrl,
          status: this.ruleForm.status,
          share_cover: this.dialogImageUrl1,
          type: this.ruleForm.type.join(','),
          content: this.ruleForm.content,
          sort: this.ruleForm.sort,
          expert_id: this.ruleForm.expert && this.ruleForm.expert.id ? this.ruleForm.expert.id : ''
        }).then(res => {
          this.getNewsList()
        })
      } else {
        newsModify({
          title: this.ruleForm.title,
          // img_url:this.ruleForm.img_url,
          share_cover: this.dialogImageUrl1,
          img_url: this.dialogImageUrl,
          status: this.ruleForm.status,
          type: this.ruleForm.type.join(','),
          content: this.ruleForm.content,
          sort: this.ruleForm.sort,
          id: this.ruleForm.id,
          expert_id: this.ruleForm.expert && this.ruleForm.expert.id ? this.ruleForm.expert.id : ''
        }).then(res => {
          this.getNewsList()
        })
      }
      this.dialogTableVisible = false
    },
    handleButton1Click(row, e) {
      this.dialogImageUrl1 = row.cover
      this.dialogImageUrl = row.cover
      this.contentData = row.content + this.tmpFoot
      this.isVisible = true
      this.ruleForm = JSON.parse(JSON.stringify(row))
      this.type = e === 'zuqiu' ? 2 : 3
      this.ruleForm.type = [this.type]
      this.dialogTableVisible = true
    },
    // 删除
    handleButton2Click(row) {
      this.$confirm('此操作将永久删除该资讯, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        newsDelete({
          id: row.id
        }).then(res => {
          this.getNewsList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleButtonAdd() {
      this.ruleForm.id = null
      this.ruleForm.type = []
      this.isVisible = true
      this.dialogTableVisible = true
    },
    clickDelete() {
      this.isVisible = false
      this.contentData = ''
      this.dialogTableVisible = false
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      console.log(res.data.url)
      console.log(URL.createObjectURL(file.raw))
      this.ruleForm.img_url = res.data.url
      this.dialogImageUrl = res.data.url
      // this.ruleForm.img_url = URL.createObjectURL(file.raw)
    }
  }
}
</script>

<style>
.addBtn {
    margin-left: 30px;
    margin-bottom: 30px;
    margin-top: 30px;
}

.zhuanjia-info {
    display: flex;
    align-items: center;
    margin-top: 10px;
}

.zhuanjia-info>img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-right: 10px;
}

.search-section {
    padding: 20px;
    background-color: #f5f5f5;
    border-radius: 4px;
    margin-bottom: 20px;
}
</style>
